package cz.acies.genea.data.process;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.JsonElement;

public abstract class AbstractProcessor
{
	private ServletContext application;
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	protected Map<String, Object> params = new HashMap<String, Object>();
	
	protected String type = "json";
	
	// -----  -----------------------------------------------------------------
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		this.setRequest(request);
		this.setResponse(response);
		
		params = makeParams(request);
		try {
			if (this.type.equals("json")) {				
				response.setContentType("text/plain");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				String result = executeCommand(params);
				out.print(result);
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	
	public abstract String executeCommand(Map<String, Object> params);
	
	protected Map<String, Object> makeParams(HttpServletRequest request) {
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String key = e.nextElement();
			params.put(key, request.getParameter(key));
		}
		return params;
	}
	
	// -----  -----------------------------------------------------------------
	
	public ServletContext application() {
		return application;
	}
	
	public void setServletContext(ServletContext application) {
		this.application = application;
	}
	
	public HttpSession getSession() {
		return session;
	}
	
	public void setSession(HttpSession session) {
		this.session = session;
	}
	
	public HttpServletRequest request() {
		return request;
	}
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public HttpServletResponse response() {
		return response;
	}
	
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
}
